<template>
    <div>
        <!-- 地址管理 -->
        <!-- 头部导航 -->
        <van-nav-bar title="地址" left-text="返回" left-arrow @click-left="$router.go(-1)" />
        <!-- AddressList 地址列表组件 -->
        <van-address-list v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit" />
        <!-- 新增信息组件 -->
        <van-popup v-model:show="showAdd" position="bottom">
            <van-address-edit :area-list="areaList" show-postal show-delete show-set-default show-search-result
                :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="ADDonSave"
                @delete="showAdd = false" :address-info="AddressEditInfo" />
        </van-popup>
        <!-- 编辑信息组件 -->
        <van-popup v-model:show="showEdit" position="bottom">
            <van-address-edit :area-list="areaList" show-postal show-delete show-set-default show-search-result
                :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="EditonSave"
                @delete="onDeleteEdit" :address-info="AddressEditInfo" />
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { Toast } from 'vant'
import { areaList } from '@vant/area-data';
import { useUserStore } from '@/store/useUserStore'
import { addressListApi, addAddress, updateAddress, delAddress } from '@/api/addressApi'
import { ref, type Ref, reactive, computed, watch, defineProps, defineEmits } from 'vue'


export interface addAddressobj {
    userid: string,
    name: string,
    tel: string,
    province: string,
    city: string,
    county: string,
    addressDetail: string
    isDefault: boolean
}
export interface addressobj1 {
    id: string
    name: string,
    tel: string
    address: string
    isDefault: boolean
    province?: string
    city?: string
    county?: string
    addressid: string
}


const UserStore = useUserStore()
// 双向绑定数据- 地址选项卡片id（默认选择）
let chosenAddressId = ref()
// 地址信息初始值
const AddressEditInfo: Ref<addAddressobj | object> = ref({})
// 定义地址列表数组
let list: Ref<Array<addressobj1>> = ref([])
let showAdd = ref(false)
// 地址的id
let index=0


function getaddress() {
    addressListApi({ userid: UserStore.userid }).then((res: any) => {
        console.log('地址列表数据', res);
        // 先让清空list
        list.value = []
        if (res.code == 200) {
            res.data.forEach((item: any, index: number) => {
                list.value.push({
                    id: String(index + 1),
                    name: item.name,
                    tel: item.tel,
                    address: item.addressDetail,
                    isDefault: item.isDefault,
                    province: item.province,
                    city: item.city,
                    county: item.county,
                    addressid: item.addressid
                })
                if (item.isDefault) {
                    chosenAddressId.value = String(index + 1)
                }
            })
        }
    })
}
getaddress()

let onAdd = () => {
    //新增地址
    // 新增地址
    AddressEditInfo.value = {}
    showAdd.value = true
}

const ADDonSave = (item: any) => {
    // 新增地址
    let valus: addAddressobj = {
        userid: UserStore.userid as string,
        name: item.name,
        tel: item.tel,
        province: item.province,
        city: item.city,
        county: item.county,
        addressDetail: item.addressDetail,
        isDefault: item.isDefault,
    }
    addAddress(valus).then((res: any) => {
        if (res.code == 200) {
            getaddress()//重新渲染
            showAdd.value = false
        }
    })

}

// 编辑方法
// 回调参数item: AddressListAddress, index: number
let showEdit = ref(false)//编辑地址弹出框默认隐藏
let areaCode = ref<string>("")//地区编码
let onEdit = (item: any, ind: number) => {
    index=ind
    showEdit.value = true
    console.log('AddressListAddress', item, ind);
    console.log('城市级联', areaList);
    areaCode.value = ''
    // 处理省市区数据
    for (let key in areaList.province_list) {
        if ((areaList as any).province_list[key] === item.province) {
            areaCode.value += key.slice(0, 2)
        }
    }
    for (let key in areaList.city_list) {
        if ((areaList as any).city_list[key] == item.city) {
            if (key.slice(0, 2) == areaCode.value) {
                areaCode.value += key.slice(2, 4)
            }
        }
    }
    for (let key in areaList.county_list) {
        if ((areaList as any).county_list[key] === item.county) {
            if (key.slice(0, 4) == areaCode.value) {
                areaCode.value += key.slice(4)
            }
        }
    }

    // 信息回填
    AddressEditInfo.value = {
        name: item.name,
        tel: item.tel,
        addressDetail: item.address,
        areaCode: areaCode,  //地区
        postalCode: item.postalCode,
        isDefault: item.isDefault,
        province: item.province,
        city: item.city,
        county: item.county,
    }
    // index = index
}

// 保存修改后的地址
// 该事件触发的方法要传回调参数：content：表单内容

const EditonSave = (item: any) => {
    console.log('地址信息）修改',item);
    
    const values = {
        addressid: list.value[index].addressid,
        userid: UserStore.userid as string,
        name: item.name,
        tel: item.tel,
        province: item.province,
        city: item.city,
        county: item.county,
        addressDetail: item.addressDetail,
        isDefault: item.isDefault,
    }
    console.log('xiugai',values.addressid);
    
    updateAddress(values).then((res: any) => {
        console.log('更新',res);
        console.log(item,123123);
        
        if (res.code == 200) {
            list.value = []
            getaddress()//重新渲染
            showEdit.value = false//隐藏编辑组件 
        }
        
    })

}


const searchResult = ref([]);



// 删除
const onDeleteEdit = () => { 

    
    console.log(list.value[index]?.addressid);
    
    delAddress({
        addressid: list.value[index].addressid
    }).then((res: any) => {
        if (res.code == 200) {
            getaddress()
            showEdit.value = false
        }
    })
}




</script>
<style scoped lang="scss">
.van-nav-bar {
    color: red;
}
</style>